/* Copyright (c) 2011, Damjan Jovanovic <damjan dot jov aaa aaatt t tt gmail>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the author nor the
 *       names of the contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package com.googlecode.raisinrefinery;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

public class Main {
    private String revisions;
    private File sourceDir;
    private File binaryDir;
    private static String[] goodPrefixes = {"dlls/", "programs/"};
    private static String[] goodSuffixes = {".c", ".h", ".spec", ".rc", ".js", ".y", ".l"};
    private static String[] goodFiles = {".gitignore", "ANNOUNCE"};

    public Main(String revisions, File sourceDir, File binaryDir) {
        this.revisions = revisions;
        this.sourceDir = sourceDir;
        this.binaryDir = binaryDir;
    }

    public void run() throws IOException {
    	if (!binaryDir.exists()) {
    		binaryDir.mkdir();
    	}
    	gitInit();
    	
        LinkedList<String> revisionList = gitRevList(revisions);
        String latestRevision = latestCommit();
        Iterator<String> it;
        int total = revisionList.size();
        if (latestRevision == null) {
            it = revisionList.descendingIterator();
            System.out.println("Starting from scratch, " + revisionList.size() +
                    " revisions remain");
        } else {
            for (it = revisionList.descendingIterator(); it.hasNext();) {
                String revision = it.next();
                --total;
                if (revision.equals(latestRevision)) {
                    break;
                }
            }
            if (!it.hasNext()) {
                throw new IOException("Latest commit " + latestRevision +
                        " is not inside the revision range specified");
            }
            System.out.println("Resuming from commit " + latestRevision +
                    ", " + total + " revisions remain");
        }
        
        int done = 0;
        BooleanHolder haveCompiledAnything = new BooleanHolder();
        for (; it.hasNext();) {
            String revision = it.next();
            compileAndCommit(haveCompiledAnything, revision);

            ++done;
            System.out.println("Processed " + done + "/" + total + " revisions");
        }
    }

    private void compileAndCommit(BooleanHolder haveCompiledAnything, String revision) throws IOException {
        // Patches not compiling is so common that this list is far from exhaustive:
        if (!PatchBackporter.canCompileRevision(revision)) {
            System.out.println("Skipping commit " + revision + " because it doesn't compile");
            return;
        }
        System.out.println("Compiling commit " + revision);
        resetToRevision(revision);
        BooleanHolder changedConfigure = new BooleanHolder();
        PatchBackporter.backportPatches(sourceDir, revision);
        if (!haveCompiledAnything.value || commitModificationsHadGlobalEffects(revision, changedConfigure)) {
            // bad news: recompile everything
            if (!haveCompiledAnything.value) {
                changedConfigure.value = true;
            }
            if (changedConfigure.value) {
                System.out.println("Very slow path");
            } else {
                System.out.println("Slow path");
            }
            gitClean();
            configure(changedConfigure.value);
            try {
                // commit a45c2484e08046653ec8cab077f802a574b82114 fails to "make depend"...
                makeDepend();
            } catch (IOException ioEx) {
                ioEx.printStackTrace();
                System.out.println("Commit " + revision + " FAILED TO make depend, skipping it");
                // start cleanly for the next commit, just in case:
                haveCompiledAnything.value = false;
                return;
            }
        }
        if (!make()) {
            System.out.println("Commit " + revision + " FAILED TO COMPILE, skipping it");
            // start cleanly for the next commit, just in case:
            haveCompiledAnything.value = false;
            return;
        }
        deleteBinaries(binaryDir);
        try {
            makeInstallFast();
        } catch (IOException ioEx) {
            deleteBinaries(binaryDir);
            try {
                makeInstall();
            } catch (IOException ioEx2) {
                // Unbelievable. I am speechless.
                // A chain of at least 8 patches doesn't "make install".
                // Don't bother trying, just keep skipping until something does....
                System.out.println("Commit "  + revision + " FAILED TO make install, skipping it");
                haveCompiledAnything.value = false;
                return;
            }
        }
        commitBinaries(revision);
        haveCompiledAnything.value = true;
    }

    private void gitInit() throws IOException {
    	for (File file : binaryDir.listFiles()) {
    		if (file.getName().equals(".git")) {
    			return;
    		}
    	}
    	ProcessUtils.runAndCollectOutputFor(binaryDir, null, "git", "init");
    }
    
    private LinkedList<String> gitRevList(String revisions) throws IOException {
        LinkedList<String> output = ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "git", "rev-list", revisions);
        // add the first commit, which "git rev-list" excludes
        int pos = revisions.indexOf("..");
        output.addLast(revisions.substring(0, pos));
        return output;
    }

    private String latestCommit() throws IOException {
        LinkedList<String> output;
        try {
            output = ProcessUtils.runAndCollectOutputFor(binaryDir, null,
                    "git", "log", "-1", "HEAD");
        } catch (IOException ioEx) {
            return null;
        }
        output.removeFirst();
        output.removeFirst();
        output.removeFirst();
        output.removeFirst();
        String line = output.removeFirst();
        line = line.trim();
        return line.substring("Original commit ".length());
    }

    private void resetToRevision(String revision) throws IOException {
        ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "git", "reset", "--hard", revision);
    }

    private void deleteBinaries(File dir) throws IOException {
        for (File file : dir.listFiles()) {
            if (file.getName().startsWith(".")) {
                continue;
            }
            if (file.isDirectory()) {
                deleteBinaries(new File(dir, file.getName()));
                file.delete();
            } else {
                file.delete();
            }
        }
    }

    private void gitClean() throws IOException {
        ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "git", "clean", "-fd");
    }

    private void configure(boolean changedConfigure) throws IOException {
        Map<String,String> map = new HashMap<String, String>();
        map.put("CFLAGS", "-O0");
        ArrayList<String> args = new ArrayList<String>();
        args.add("./configure");
        if (!changedConfigure) {
            args.add("-C");
        }
        args.add("--disable-tests");
        args.add("--disable-win16"); // Win16 from early 1.x Wines fails to "make install"
        args.add("--prefix=" + binaryDir.getCanonicalPath());
        ProcessUtils.runAndCollectOutputFor(sourceDir, map,
            args.toArray(new String[0]));
    }

    private void makeDepend() throws IOException {
        ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "make", "-j", "" + Runtime.getRuntime().availableProcessors(), "depend");
    }

    private boolean make() {
        // Some patches always fail to compile, so
        // assume make failing to be normal...
        try {
            ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                    "make", "-j", "" + Runtime.getRuntime().availableProcessors());
            return true;
        } catch (IOException ioEx) {
            ioEx.printStackTrace();
            return false;
        }
    }

    private void makeInstallFast() throws IOException {
        ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "make", "-j", "" + Runtime.getRuntime().availableProcessors(), "install");
    }

    private void makeInstall() throws IOException {
        // at least commit fb17ae0b833ab42fa6da8c72f70adb8bb3a5438a
        // fails with "make -j 4 install", but succeeds with
        // "make install" .......
        ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "make", "install");
    }

    private void commitBinaries(String revision) throws IOException {
        for (File file : binaryDir.listFiles()) {
            if (file.getName().startsWith(".")) {
                continue;
            }
            ProcessUtils.runAndCollectOutputFor(binaryDir, null,
                    "git", "add", new File(binaryDir, file.getName()).getCanonicalPath());
        }
        ProcessUtils.runAndCollectOutputFor(binaryDir, null,
                "git", "commit", "-a", "-m",
                "Original commit " + revision);
    }

    private boolean commitModificationsHadGlobalEffects(String revision, BooleanHolder changedConfigure) throws IOException {
        LinkedList<String> filesModified = getFilesModified(revision);
        for (String file : filesModified) {
            System.out.println("Commit affected " + file);
            if (file.equals("configure") || file.equals("configure.ac")) {
                changedConfigure.value = true;
            }
            boolean prefixFound = false;
            for (String prefix : goodPrefixes) {
                if (file.startsWith(prefix)) {
                    prefixFound = true;
                    break;
                }
            }
            boolean suffixFound = false;
            for (String suffix : goodSuffixes) {
                if (file.endsWith(suffix)) {
                    suffixFound = true;
                    break;
                }
            }
            if (!prefixFound || !suffixFound) {
                boolean fileFound = false;
                for (String goodFile : goodFiles) {
                    if (file.equals(goodFile)) {
                        fileFound = true;
                        break;
                    }
                }
                return !fileFound;
            }
        }
        return false;
    }

    private LinkedList<String> getFilesModified(String revision) throws IOException {
        LinkedList<String> output = ProcessUtils.runAndCollectOutputFor(sourceDir, null,
                "git", "log", "-1", "--name-only", revision);
        LinkedList<String> ret = new LinkedList<String>();
        for (Iterator<String> it = output.descendingIterator(); it.hasNext(); ) {
            String line = it.next();
            if (line.trim().length() == 0) {
                break;
            }
            ret.addFirst(line);
        }
        return ret;
    }

    public static void safelyClose(Closeable c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException ioEx) {
        }
    }

    public static void safelyClose(ServerSocket c) {
        try {
            if (c != null) {
                c.close();
            }
        } catch (IOException ioEx) {
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
    	boolean matched = true;
    	if (args.length > 1) {
    		if (args[0].equals("build") && args.length == 4) {
                String revisions = args[1];
                String sourcePath = args[2];
                String binaryPath = args[3];
                Main main = new Main(revisions, new File(sourcePath), new File(binaryPath));
                main.run();
    		} else if (args[0].equals("patch") && args.length == 3) {
            	PatchBackporter.backportPatches(new File(args[1]), args[2]);
    		} else {
    			matched = false;
    		}
        } else {
        	matched = false;
        }
    	if (!matched) {
            System.err.println("Arguments must one of:");
            System.err.println("    build firstCommitSHA1..lastCommitSHA1 /path/to/wine-source /path/to/wine-binaries - builds a Git repository of Wine binaries");
            System.err.println("    patch /path/to/wine-source revision - applies patches needed to compile that Wine source revision");
            System.exit(1);
        }

    }

}
